package com.chengqj.service.impl;

import com.chengqj.dao.OrderDO;
import com.chengqj.repository.OrderRepository;
import com.chengqj.service.IOrderService;
import com.chengqj.service.IUserService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * Copyright © 2020年 com.qxkj. All rights reserved.
 *
 * @author chengqj
 * TODO: 为了共建和谐社会，请为该类写点注释吧...
 * version 1.0.0 (接口必须带上)
 * @date 2020/11/6 15:32
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;
    @DubboReference
    private IUserService userService;
    @Override
    public boolean prepare(BusinessActionContext actionContext, String userId) {
        String xid = RootContext.getXID();
        System.out.println("TccActionOne prepare, xid:" + xid + ", a:" + userId);
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        System.out.println("order   commit ++++++++++++++++ ");
        String userId = (String) actionContext.getActionContext("userId");
        OrderDO orderDO = new OrderDO();
        orderDO.setUserId(userId);
        orderDO.setAmount(BigDecimal.ONE);
        orderDO.setGmtCreate(LocalDateTime.now());
        orderRepository.save(orderDO);

        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext actionContext) {
        String xid = RootContext.getXID();
        String userId = (String) actionContext.getActionContext("userId");
        System.out.println("rollback + ++++++++++++++++");
        return true;
    }
}
